package com.ingenius.sau.server.persistence.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.ingenius.sau.server.service.BlobFile;

public class JdoBlobFileDAO {

	private static JdoBlobFileDAO instance = null;

	private JdoBlobFileDAO() {
	}

	public static JdoBlobFileDAO getInstance() {
		if (instance == null) {
			instance = new JdoBlobFileDAO();
		}
		return instance;
	}

	public String save(BlobFile photo) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(photo);
		} finally {
			pm.close();
		}
		return photo.getId();
	}

	public BlobFile getById(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(BlobFile.class);
		query.setFilter("id == idParam");
		query.declareParameters("String idParam");
		List<?> photo = null;
		try {
			photo = (List<?>) query.execute(id);
			if (photo.isEmpty()) {
				return null;
			} else {
				return (BlobFile) photo.get(0);
			}

		} finally {
			query.closeAll();
		}
	}

	public boolean delete(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(BlobFile.class);
		query.setFilter("id == idParam");
		query.declareParameters("String idParam");
		List<?> photo = null;
		try {
			photo = (List<?>) query.execute(id);
			if (photo.isEmpty()) {
				return false;
			} else {
				pm.deletePersistent(photo.get(0));
				return true;
			}

		} finally {
			query.closeAll();
		}
	}
}
